import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Layout, theme, Space } from 'antd';
import AuthModule from './auth/AuthModule';
import SessionModule from './auth/SessionModule';
import ProtectedModule from './auth/ProtectedModule';
import MessageModule from './auth/MessageModule';
import { 
  MessageOutlined, 
  RobotOutlined, 
  LoginOutlined, 
  LogoutOutlined 
} from '@ant-design/icons';
import { 
  login, 
  logout, 
  fetchProtectedData, 
  getStorageStatus
} from '../api/auth';
import HeaderBar from './common/HeaderBar';
import { Alert, Button } from 'antd';

const { Header, Content } = Layout;

const AuthPage = () => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState<{ username: string } | null>(null);
  const [protectedData, setProtectedData] = useState(null);
  const [storageType, setStorageType] = useState('unknown');
  const [message, setMessage] = useState('');
  const [status, setStatus] = useState('未登录');
  const { token: { colorBgContainer, borderRadiusLG } } = theme.useToken();
  const navigate = useNavigate();
  
  // 使用 useEffect 安全地设置 CSS 变量
  useEffect(() => {
    document.documentElement.style.setProperty('--colorBgContainer', colorBgContainer);
    document.documentElement.style.setProperty('--borderRadiusLG', `${borderRadiusLG}px`);
  }, [colorBgContainer, borderRadiusLG]);

  // 检查认证状态
  useEffect(() => {
    const checkAuth = async () => {
      try {
        const data = await getStorageStatus();
        setStorageType(data.storage_type);
        if (data.storage_type !== 'unknown') {
          setIsAuthenticated(true);
          // 修正：使用对象设置用户
          setUser({ username: 'admin' });
          setStatus('已登录');
        }
      } catch (error: unknown) {
        console.log(`Not authenticated: ${error instanceof Error ? error.message : '未知错误'}`);
      }
    };
    
    checkAuth();
  }, []);

  const handleLogin = async (username: string, password: string) => {
    try {
      const result = await login(username, password);
      setIsAuthenticated(true);
      // 修正：使用对象设置用户
      setUser({ username });
      setStatus('已登录');
      setMessage(`登录成功！刷新令牌: ${result.refresh_token.substring(0, 10)}...`);
      await checkStorageType();
      navigate('/chat', { replace: true });
    } catch (error: unknown) {
      setMessage(`登陆失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  };

  const handleLogout = async () => {
    try {
      await logout();
      setIsAuthenticated(false);
      // 修正：退出时设置为 null
      setUser(null);
      setProtectedData(null);
      document.cookie = 'access_token=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
      setStatus('未登录');
      setMessage('已成功退出登录');
    } catch (error: unknown) {
      setMessage(`退出登录失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };

  const handleFetchProtectedData = async () => {
    try {
      const data = await fetchProtectedData();
      setProtectedData(data);
      setMessage('成功获取受保护内容');
    } catch (error: unknown) {
      setMessage(`获取受保护内容失败:${error instanceof Error ? error.message : '未知错误'}`);
    }
  };

  const checkStorageType = async () => {
    try {
      const data = await getStorageStatus();
      setStorageType(data.storage_type);
      setMessage(`存储状态更新: ${data.storage_type}`);
    } catch (error: unknown) {
      setMessage(`获取存储状态失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };

  const handleRefreshToken = async () => {
    setMessage('访问令牌已刷新');
  };

  return (
    <Layout style={{ minHeight: '100vh', width: '100%' }}>
      <HeaderBar />
      <Content
        style={{
          padding: '24px 48px',
          background: '#f0f2f5',
          minHeight: 'calc(100vh - 64px)'
        }}
      >
        <div
          style={{
            background: colorBgContainer,
            minHeight: 'calc(100vh - 112px)',
            padding: 24,
            borderRadius: borderRadiusLG,
            boxShadow: '0 2px 8px rgba(0,0,0,0.05)'
          }}
        >
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            <AuthModule
              isAuthenticated={isAuthenticated}
              // 修正：直接传递 user 对象
              user={user}
              onLogin={handleLogin}
              onLogout={handleLogout}
            />
            
            {isAuthenticated && (
              
              <>
                <Link to="/chat-page">
                    <Button type="primary" size="large">
                        <RobotOutlined /> Chat Page
                    </Button>
                </Link>
                <SessionModule 
                  storageType={storageType}
                  onRefreshStorage={checkStorageType}
                  onRefreshToken={handleRefreshToken}
                />
                
                <ProtectedModule 
                  isAuthenticated={isAuthenticated}
                  protectedData={protectedData}
                  onFetchData={handleFetchProtectedData}
                />
              </>
            )}
            
            <MessageModule 
              message={message}
              status={status}
            />
          </Space>
        </div>
      </Content>
    </Layout>
  );
}

export default AuthPage;